package com.hupu.selenium.jop;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import com.hupu.selenium.jop.constant.CDNServiceProviders;
import com.hupu.selenium.jop.util.PreventLinkUtil;
import com.hupu.selenium.jop.util.PropertiesUtils;

public class CutCDNTime {
	
	private Integer cdnProviderType = null;
	private String chromeUrl = null;
	private Integer cutImageTime = null;
	private String streamName = null;
	private String fs = System.getProperties().getProperty("file.separator");
	private Map<Integer,String []> cdnProviders = new HashMap<Integer,String[]>();
	
	/**
	 * 初始化参数
	 */
	private void initalize(){
		
		Properties pro = PropertiesUtils.getProperties();
		//帝联(1),蓝汛(2),乐视(3),快网(4),网宿(5)
		//String数组第一个是CND供应商名称，第二个是测试拉流播放地址，第三个是推流地址，第四个是拉流地址
		String [] s1 = {"帝联",pro.getProperty("hupu.pull.stream.page.dilian"),pro.getProperty("hupu.push.stream.url.dilian"),pro.getProperty("hupu.pull.stream.url.dilian")};
		cdnProviders.put(1,s1);
		String [] s2 = {"蓝汛",pro.getProperty("hupu.pull.stream.page.lanxun"),pro.getProperty("hupu.push.stream.url.lanxun"),pro.getProperty("hupu.pull.stream.url.lanxun")};
		cdnProviders.put(2,s2);
		String [] s3 = {"乐视",pro.getProperty("hupu.pull.stream.page.leshi"),pro.getProperty("hupu.push.stream.url.leshi"),pro.getProperty("hupu.pull.stream.url.leshi")};
		cdnProviders.put(3,s3);
		String [] s4 = {"快网",pro.getProperty("hupu.pull.stream.page.kuaiwang"),pro.getProperty("hupu.push.stream.url.kuaiwang"),pro.getProperty("hupu.pull.stream.url.kuaiwang")};
		cdnProviders.put(4,s4);
		String [] s5 = {"网宿",pro.getProperty("hupu.pull.stream.page.wangsu"),pro.getProperty("hupu.push.stream.url.wangsu"),pro.getProperty("hupu.pull.stream.url.wangsu")};
		cdnProviders.put(5,s5);
		
		//初始化chrome浏览器地址
		chromeUrl = pro.getProperty("hupu.chrom.url");
		chromeUrl = chromeUrl == null?"http://localhost:9515":chromeUrl;
		
		//初始化要截图CDN提供商类型（默认全部要截图）
		try {
			cdnProviderType = Integer.valueOf(pro.getProperty("hupu.cdn.provider.type") == null?"0":pro.getProperty("hupu.cdn.provider.type"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cdnProviderType = 0;
		}
		boolean tmp = false;
		for(CDNServiceProviders sp:CDNServiceProviders.values()){
			if(cdnProviderType.equals(sp.getType())){
				tmp = true;
				break;
			}
		}
		if(!tmp)
			cdnProviderType = 0;
		
		//初始化截图时间间隔（默认600秒）
		try {
			cutImageTime = Integer.valueOf(pro.getProperty("hupu.cut.image.time") == null?"600":pro.getProperty("hupu.cut.image.time"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
			cutImageTime = 600;
		}
		
		//初始化拉流名
		streamName = pro.getProperty("hupu.stream.name") == null?null:pro.getProperty("hupu.stream.name");
		if(streamName ==  null ||  "".equals(streamName.trim()))
			streamName = UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	private void start(CutCDNTime cutCDNTime) throws Exception{
		if(cdnProviderType == 0){
			for(Integer t:cdnProviders.keySet()){
				cutCDNTime.new AllCutImage(cutCDNTime,t).start();
				Thread.sleep(500);
			}
		}else{
			cutCDNTime.exceCMD(cdnProviderType);
			cutCDNTime.cutImage(cdnProviderType);
		}
	}
	
	class AllCutImage extends Thread{
		
		private CutCDNTime cutCDNTime;
		private Integer type;

		public AllCutImage(CutCDNTime cutCDNTime, Integer type) {
			super();
			this.cutCDNTime = cutCDNTime;
			this.type = type;
		}

		public void run() {
			super.run();
			
			try {
				cutCDNTime.exceCMD(type);
				cutCDNTime.cutImage(type);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private void exceCMD(Integer type) throws Exception{
		//执行命令
		StringBuffer cmd = new StringBuffer();
		cmd.append("ffmpeg ");
		cmd.append("-f x11grab -framerate 30 -video_size 1280x720 -i :0.0+0,0 -vcodec libx264 -preset veryfast -maxrate 1984k -bufsize 3968k ");
		cmd.append("-vf \"format=yuv420p,drawtext='fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf:text=%{localtime\\:%Y-%m-%d %H.%M.%S}:fontcolor=red:fontsize=60'\" ");
		cmd.append("-g 60 -acodec libmp3lame -b:a 96k -ar 44100 -f flv '");
		cmd.append(getPushStreamUrl(type, cdnProviders.get(type),streamName));
		cmd.append("'");
		System.out.println("CDN提供商:"+cdnProviders.get(type)[0]+";流名称:"+streamName+";推流地址:"+cmd.toString());
		
	}
	
	private void cutImage(Integer type) throws Exception{
		WebDriver dr = new RemoteWebDriver(new URL(chromeUrl),DesiredCapabilities.chrome());
        dr.get(cdnProviders.get(type)[1]);
        
        resetPreventLink(dr, type, cdnProviders.get(type),streamName);
                  
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        while(true){
        	Thread.sleep(60000);
            File screenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
            StringBuffer sb = new StringBuffer();
            sb.append("images");
            sb.append(fs);
            sb.append("CDN延时截图");
            sb.append(fs);
            sb.append(sdf2.format(new Date()));
            sb.append(fs);
            sb.append(cdnProviders.get(type)[0]);
            sb.append(fs);
            sb.append(cdnProviders.get(type)[0]);
            sb.append("CDN延时截图");
            sb.append(sdf1.format(new Date()));
            sb.append(".png");
            FileUtils.copyFile(screenShotFile, new File(sb.toString()));
            Thread.sleep(cutImageTime*1000);
            resetPreventLink(dr, type, cdnProviders.get(type),streamName);
        }
	}
	
	private static void resetPreventLink(WebDriver dr, Integer type, String [] urls, String streamName) throws Exception{
		 JavascriptExecutor js = (JavascriptExecutor)dr;
	     WebElement body = dr.findElement(By.tagName("body"));
	     js.executeScript(getUpdateSwfHtmlJS(type,urls,streamName), body);
	}
	
	private static String getUpdateSwfHtmlJS(Integer type, String [] urls, String streamName) throws Exception{
		
		String url = "";
		switch(type){
			case 1:url = urls[3]+"/"+ URLEncoder.encode(streamName+"?"+PreventLinkUtil.getPreventLink(2,1, "test_dilian_pull", streamName, new Date().getTime()));break;
			case 2:url = urls[3]+"?"+URLEncoder.encode(URLDecoder.decode( PreventLinkUtil.getPreventLink(2,2, "test_lanxun_pull", streamName, new Date().getTime()))+"/"+streamName);break;
			case 3:url = urls[3]+"/"+ URLEncoder.encode(streamName);break;
			case 4:url = urls[3]+"/"+URLEncoder.encode(PreventLinkUtil.getPreventLink(2,4, "test_kuaiwang", streamName, new Date().getTime()));break;
			case 5: url = urls[3]+"/"+ URLEncoder.encode(streamName+"?"+PreventLinkUtil.getPreventLink(2,5, "test_wangsu_pull", streamName, new Date().getTime())); break;
			default: throw new Exception("拉流类型不存在//帝联(1),蓝汛(2),乐视(3),快网(4),网宿(5)");
		}
		
		StringBuffer sb = new StringBuffer();
        sb.append("swfobject.removeSWF('FlashContainer');");
        
        sb.append("var divElement = document.createElement('div');");
		sb.append("divElement.id = 'FlashContainer';");
		sb.append("document.body.appendChild(divElement);");
        
        sb.append("swfobject.embedSWF('wsPlayer.swf', 'FlashContainer', '640', '400', '9.0.0', '', {");
//		sb.append("	url: encodeURIComponent('"+url+"'),");
		sb.append("	url: '"+url+"',");
		sb.append("	isSeekAsTime: 'false',");
		sb.append(" 	isLive: 'true'");
		sb.append("}, {");
		sb.append("	allowfullscreen: 'true',");
		sb.append("	quality: 'high'");
        sb.append("});");
        return sb.toString();
	}
	
	private static String getPushStreamUrl(Integer type, String [] urls, String streamName) throws Exception{
		String pushUrl = "";
		switch(type){
			case 1:pushUrl= urls[2]+"/"+streamName+"?"+PreventLinkUtil.getPreventLink(1,1, "test_dilian", streamName, new Date().getTime());break;
			case 2:pushUrl = urls[2]+"?"+URLDecoder.decode( PreventLinkUtil.getPreventLink(1,2, "test_lanxun", streamName, new Date().getTime()))+"/"+streamName;break;
			case 3:pushUrl  = urls[2]+"/"+streamName;break;
			case 4:pushUrl  = urls[2]+"/"+PreventLinkUtil.getPreventLink(1,4, "test_kuaiwang", streamName, new Date().getTime());break;
			case 5: pushUrl  = urls[2]+"/"+streamName+"?"+PreventLinkUtil.getPreventLink(1,5, "test_wangsu",streamName, new Date().getTime()); break;
			default: throw new Exception("拉流类型不存在//帝联(1),蓝汛(2),乐视(3),快网(4),网宿(5)");
		}
		return pushUrl;
	}
	
	public static void main(String[] args) throws Exception {
		
		CutCDNTime cutCDNTime = new CutCDNTime();
		cutCDNTime.initalize();
		
		//启动拉流测试
		cutCDNTime.start(cutCDNTime);
	}
	
}